const http = require('http');
const fs = require('fs');
const path = require('path');

// 服务器配置
const PORT = 8080;
const HOST = 'localhost';
const PUBLIC_DIR = path.join(__dirname, '.');

// 创建服务器
const server = http.createServer((req, res) => {
    // 记录请求
    console.log(`接收到请求: ${req.method} ${req.url} 来自 ${req.headers['user-agent']}`);
    // 获取请求的文件路径
    let filePath = path.join(PUBLIC_DIR, req.url === '/' ? '/modern-skills-list.html' : req.url);

    // 获取文件扩展名
    const extname = String(path.extname(filePath)).toLowerCase();

    // 定义MIME类型
    const mimeTypes = {
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.css': 'text/css',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.gif': 'image/gif',
        '.svg': 'image/svg+xml',
        '.wav': 'audio/wav',
        '.mp4': 'video/mp4',
        '.woff': 'application/font-woff',
        '.ttf': 'application/font-ttf',
        '.eot': 'application/vnd.ms-fontobject',
        '.otf': 'application/font-otf',
        '.wasm': 'application/wasm'
    };

    // 设置内容类型
    const contentType = mimeTypes[extname] || 'application/octet-stream';

    // 读取文件
    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code === 'ENOENT') {
                // 文件不存在
                res.writeHead(404, { 'Content-Type': 'text/html' });
                res.end('<h1>404 Not Found</h1>', 'utf-8');
            } else {
                // 服务器错误
                res.writeHead(500);
                res.end(`Server Error: ${error.code} ..\n`);
            }
        } else {
            // 成功响应
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf-8');
        }
    });
});

// 启动服务器
server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}/`);
    console.log(`预览现代化技能列表页面: http://${HOST}:${PORT}/modern-skills-list.html`);
});

// 处理服务器错误
server.on('error', (e) => {
    if (e.code === 'EADDRINUSE') {
        console.error(`Port ${PORT} is already in use`);
    } else {
        console.error('Server error:', e);
    }
});